//
//  BCMUserSettingViewController.m
//  BCManagerVersion
//
//  Created by ZhaoXiang on 3/7/14.
//  Copyright (c) 2014 Jungle. All rights reserved.
//

#import "BCMUserSettingViewController.h"
#import "UIAlertView+Blocks.h"
#import "BCMTitleValueCell.h"
#import "BCMTextFieldCell.h"
#import "UIActionSheet+Blocks.h"
#import "BCPublishViewController.h"
#import "BCProgressHUD.h"
#import "EXTScope.h"
#import "UIViewController+EndWhenTouch.h"

#define TYPE_TEXT_FIELD 0
#define TYPE_TITLE_VALUE 1

#define TITLE 0
#define KEY 1
#define TYPE 2
#define KEYBOARD_TYPE 3
#define TEXT_LENGTH 4
@interface BCMUserSettingViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) NSArray* configure;
@property (nonatomic, strong) NSArray* works;
@property (nonatomic, strong) NSArray* banks;
@property (nonatomic, strong) NSIndexPath* editingIndexPath;
@end

@implementation BCMUserSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.configure = @[
                           @[@"姓名", @"name", @(TYPE_TEXT_FIELD), @(UIKeyboardTypeDefault), @5],
                           @[@"性别", @"genderString", @(TYPE_TITLE_VALUE), @(UIKeyboardTypeDefault)],
                           @[@"年龄", @"age", @(TYPE_TEXT_FIELD), @(UIKeyboardTypeNumberPad), @3],
                           @[@"从业年限", @"workTimeString", @(TYPE_TITLE_VALUE), @(UIKeyboardTypeDefault)],
                           @[@"业务1", @"workType1", @(TYPE_TITLE_VALUE), @(UIKeyboardTypeDefault)],
                           @[@"业务2", @"workType2", @(TYPE_TITLE_VALUE), @(UIKeyboardTypeDefault)],
                           @[@"业务3", @"workType3", @(TYPE_TITLE_VALUE), @(UIKeyboardTypeDefault)],
                           @[@"银行", @"bankMain", @(TYPE_TITLE_VALUE), @(UIKeyboardTypeDefault)],
                           @[@"分行", @"bankSub1", @(TYPE_TEXT_FIELD), @(UIKeyboardTypeDefault), @10],
                           @[@"支行", @"bankSub2", @(TYPE_TEXT_FIELD), @(UIKeyboardTypeDefault), @10],
                           @[@"地址", @"address", @(TYPE_TEXT_FIELD), @(UIKeyboardTypeDefault), @10],
                           @[@"电话", @"tel", @(TYPE_TEXT_FIELD), @(UIKeyboardTypePhonePad), @20],
                           ];
        _regist = NO;
    }
    return self;
}

- (BOOL)enableButtons
{
    return USER_MANAGER.verified.intValue != 0;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //[self addFunctionToEndEdit];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    if (USER_MANAGER.verified.intValue == 0) {
        [self.saveButton setTitle:@"未审核" forState:UIControlStateNormal];
    }
    
    [self.tableView registerClass:[BCMTextFieldCell class]
           forCellReuseIdentifier:@"BCMTextFieldCell"];
    
    [self.tableView registerClass:[BCMTitleValueCell class]
           forCellReuseIdentifier:@"BCMTitleValueCell"];
    
    [BCProgressHUD showWithTile:@"下载中" animated:YES];
    //@weakify(self);
    [BCNetworkClient worksSuccess:^(NSArray *works) {
        self.works = @[];
        [works enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            self.works = [self.works arrayByAddingObject:obj[@"name"]];
        }];
        
        [BCNetworkClient banksSuccess:^(NSArray *banks) {
            //@strongify(self)
            self.banks = @[];
            [banks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                self.banks = [self.banks arrayByAddingObject:obj[@"name"]];
            }];
            [BCProgressHUD hideAnimated:YES];
        } failure:^(NSError *error) {
            double delayInSeconds = 0.1;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.navigationController popViewControllerAnimated:YES];
            });
            [BCProgressHUD hideWithError:error animated:YES];
            
        }];
    } failure:^(NSError *error) {
        //@strongify(self)
        double delayInSeconds = 0.1;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.navigationController popViewControllerAnimated:YES];
        });
        
        [BCProgressHUD hideWithError:error animated:YES];
    }];
    

    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.configure.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray* config = self.configure[indexPath.row];
    if ([config[TYPE] intValue] == TYPE_TITLE_VALUE) {
        BCMTitleValueCell* cell = (BCMTitleValueCell*)[tableView dequeueReusableCellWithIdentifier:@"BCMTitleValueCell" forIndexPath:indexPath];
        
        
        cell.titleLabel.text = config[TITLE];
        cell.valueLabel.text = [USER_MANAGER valueForKey:config[KEY]];
        return cell;
    } else if ([config[TYPE] intValue] == TYPE_TEXT_FIELD) {
        BCMTextFieldCell* cell = (BCMTextFieldCell*)[tableView dequeueReusableCellWithIdentifier:@"BCMTextFieldCell" forIndexPath:indexPath];
        
        cell.titleLabel.text = config[TITLE];
        cell.valueTextField.enabled = [self enableButtons];
        cell.valueTextField.text = [USER_MANAGER valueForKey:config[KEY]];
        cell.valueTextField.keyboardType = [config[KEYBOARD_TYPE] intValue];
        cell.valueTextField.delegate = self;
        cell.tag = indexPath.row;
        return cell;
    }
    return nil;
}

- (IBAction)back:(id)sender
{
    [self.view endEditing:YES];
    
    if ([self enableButtons]) {
        [UIAlertView showWithTitle:nil
                           message:@"是否保存修改？"
                 cancelButtonTitle:@"取消"
                 otherButtonTitles:@[@"保存"]
                          tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                              if (buttonIndex == 1) {
                                  [USER_MANAGER save];
                                  [BCProgressHUD showWithTile:@"上传中" animated:YES];
                                  [BCNetworkClient editAdsUserInfo:@"edit"
                                                              auth:USER_MANAGER.auth
                                                               tel:USER_MANAGER.tel
                                                          bankMain:USER_MANAGER.bankMain
                                                          bankSub1:USER_MANAGER.bankSub1
                                                          bankSub2:USER_MANAGER.bankSub2
                                                            gender:USER_MANAGER.gender
                                                               age:USER_MANAGER.age
                                                          workTime:USER_MANAGER.workTimeId
                                                          workType:[USER_MANAGER.workType componentsJoinedByString:@","]
                                                              city:USER_MANAGER.city
                                                           address:USER_MANAGER.address
                                                              name:USER_MANAGER.name
                                                           success:^{
                                                               [BCProgressHUD hideAnimated:YES];
                                                               [self.navigationController popViewControllerAnimated:YES];
                                                           } failure:^(NSError *error) {
                                                               [BCProgressHUD hideWithError:error animated:YES];
                                                           }];
                                  
                              } else {
                                  [self.navigationController popViewControllerAnimated:YES];
                              }
                              
                          }];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
    

}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    UIView* superView = textField.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    
    NSInteger row = superView.tag;
    
    self.editingIndexPath = [NSIndexPath indexPathForRow:row inSection:0];
    
    NSArray* config = self.configure[row];
    [USER_MANAGER setValue:textField.text forKey:config[KEY]];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    UIView* superView = textField.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    
    NSInteger row = superView.tag;
    
    self.editingIndexPath = [NSIndexPath indexPathForRow:row inSection:0];
    
    NSArray* config = self.configure[row];
    
    NSString* text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (text.length > [config[TEXT_LENGTH] intValue]) {
        return NO;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
    
    if (![self enableButtons])
    {
        return;
    }
    NSArray* config = self.configure[indexPath.row];
    if ([config[TYPE] intValue] == TYPE_TEXT_FIELD) {
        BCMTextFieldCell* cell = (BCMTextFieldCell*)[tableView cellForRowAtIndexPath:indexPath];
        [cell.valueTextField becomeFirstResponder];
    } else {
        BCMTitleValueCell* cell = (BCMTitleValueCell*)[tableView cellForRowAtIndexPath:indexPath];
        if ([config[KEY] isEqualToString:@"genderString"]) {
            [UIActionSheet showInView:APP_Delegate.window
                                withTitle:[NSString stringWithFormat:@"选择%@", config[TITLE]]
                        cancelButtonTitle:@"取消"
                   destructiveButtonTitle:nil
                        otherButtonTitles:@[@"男", @"女"]
                                 tapBlock:^(UIActionSheet *actionSheet, NSInteger buttonIndex) {
                                     if (buttonIndex == 0) {
                                         USER_MANAGER.gender = @0;
                                         
                                     } else if (buttonIndex == 1){
                                         USER_MANAGER.gender = @1;
                                     }
                                     cell.valueLabel.text = USER_MANAGER.genderString;
                                 }];
        } else if ([config[KEY] isEqualToString:@"workTimeString"]) {
            NSMutableArray* names = [NSMutableArray array];
            [[MangerCentre workTimes] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                [names addObject:obj[@"name"]];
            }];
            
            [UIActionSheet showInView:APP_Delegate.window
                                withTitle:[NSString stringWithFormat:@"选择%@", config[TITLE]]
                        cancelButtonTitle:@"取消"
                   destructiveButtonTitle:nil
                        otherButtonTitles:names
                                 tapBlock:^(UIActionSheet *actionSheet, NSInteger buttonIndex) {
                                     if (buttonIndex >= actionSheet.cancelButtonIndex) {
                                         return;
                                     }
                                     USER_MANAGER.workTime = [MangerCentre workTimes][buttonIndex];
                                     cell.valueLabel.text = names[buttonIndex];
                                 }];
        } else if ([config[KEY] isEqualToString:@"workType1"]
                   || [config[KEY] isEqualToString:@"workType2"]
                   || [config[KEY] isEqualToString:@"workType3"]) {
            NSMutableArray* names = [NSMutableArray arrayWithArray:self.works];
            if ([config[KEY] isEqualToString:@"workType1"]) {
                [names removeObject:USER_MANAGER.workType2];
                [names removeObject:USER_MANAGER.workType3];
            }
            else if ([config[KEY] isEqualToString:@"workType2"]) {
                [names removeObject:USER_MANAGER.workType1];
                [names removeObject:USER_MANAGER.workType3];
            }
            else if ([config[KEY] isEqualToString:@"workType3"]) {
                [names removeObject:USER_MANAGER.workType2];
                [names removeObject:USER_MANAGER.workType1];
            }
            
            [UIActionSheet showInView:APP_Delegate.window
                                withTitle:[NSString stringWithFormat:@"选择%@", config[TITLE]]
                        cancelButtonTitle:@"取消"
                   destructiveButtonTitle:nil
                        otherButtonTitles:names
                                 tapBlock:^(UIActionSheet *actionSheet, NSInteger buttonIndex) {
                                     if (buttonIndex >= actionSheet.cancelButtonIndex) {
                                         return;
                                     }
                                     [USER_MANAGER setValue:names[buttonIndex] forKey:config[KEY]];
                                     cell.valueLabel.text = names[buttonIndex];
                                 }];
        } else if ([config[KEY] isEqualToString:@"bankMain"]) {
            NSArray* names = self.banks;
            [UIActionSheet showInView:APP_Delegate.window
                            withTitle:[NSString stringWithFormat:@"选择%@", config[TITLE]]
                    cancelButtonTitle:@"取消"
               destructiveButtonTitle:nil
                    otherButtonTitles:names
                             tapBlock:^(UIActionSheet *actionSheet, NSInteger buttonIndex) {
                                 if (buttonIndex >= actionSheet.cancelButtonIndex) {
                                     return;
                                 }
                                 [USER_MANAGER setValue:names[buttonIndex] forKey:config[KEY]];
                                 cell.valueLabel.text = names[buttonIndex];
                             }];
        }
        
        
    }
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    UIEdgeInsets contentInsets;
    if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) {
        contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.height), 0.0);
    } else {
        contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.width), 0.0);
    }
    
    
    
    NSNumber *rate = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
    [UIView animateWithDuration:rate.floatValue
                     animations:^{
                         self.tableView.contentInset = contentInsets;
                         self.tableView.scrollIndicatorInsets = contentInsets;
                     }
                     completion:^(BOOL finished) {
                         [self.tableView scrollToRowAtIndexPath:self.editingIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
                     }];
    
    
    
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}


@end
